﻿using System;
using System.Linq;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace CodeCounsel.StateReports
{
    class ReportBuilder
    {
        static XNamespace XMLNS_WML = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
        static XNamespace XMLNS_DML = "http://schemas.openxmlformats.org/drawingml/2006/main";
        static XNamespace XMLNS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";

        public static byte[] CreateReport(string reportTitle, byte[] reportImage, SPWeb site)
        {
            SPFile file = site.RootFolder.Files["Template.docx"];
            using (MemoryStream documentStream = new MemoryStream())
            {
                byte[] template = file.OpenBinary();
                documentStream.Write(template, 0, template.Length);
                using (WordprocessingDocument document = WordprocessingDocument.Open(documentStream, true))
                {
                    XDocument mainPart = document.MainDocumentPart.GetXDocument();

                    XElement titleControl = mainPart.Descendants(XMLNS_WML + "sdt")
                        .Where(xe => xe.Descendants(XMLNS_WML + "tag").First().Attribute(XMLNS_WML + "val").Value == "Title")
                        .First();
                    XElement showingPlaceholder = titleControl.Descendants(XMLNS_WML + "showingPlcHdr").FirstOrDefault();
                    if (showingPlaceholder != null)
                    {
                        showingPlaceholder.Remove();
                    }
                    XElement text = titleControl.Descendants(XMLNS_WML + "t").First();
                    text.Value = reportTitle;

                    document.MainDocumentPart.FeedXDocument(mainPart);

                    XElement imageControl = mainPart.Descendants(XMLNS_WML + "sdt")
                        .Where(xe => xe.Element(XMLNS_WML + "sdtPr").Element(XMLNS_WML + "tag").Attribute(XMLNS_WML + "val").Value == "Image")
                        .First();
                    string relationshipID = imageControl.Descendants(
                        XMLNS_DML + "blip").First().Attribute(XMLNS_REL + "embed").Value;
                    OpenXmlPart imagePart = document.MainDocumentPart.GetPartById(relationshipID);
                    using (Stream stream = imagePart.GetStream(FileMode.Create, FileAccess.Write))
                    {
                        stream.Write(reportImage, 0, reportImage.Length);
                    }
                    document.Close();
                    return documentStream.ToArray();
                }
            }
        }
    }
}
